package com.hs.utils;

import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 何森
 * @since 2023-07-24-15:39
 */
public class BeanCopyUtil {

    private BeanCopyUtil() {}

    // 单对象属性拷贝
    public static <T,R> R copyBean(T source, Class<R> clazz) {
        R target = null;
        try {
            target = clazz.newInstance();
            BeanUtils.copyProperties(source, target);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return target;
    }

    // 集合多对象拷贝
    public static <T,R> List<R> copyBeanList(List<T> list,Class<R> clazz) {
        return list == null ? null : list.stream().map(element -> {
            R target = null;
            try {
                target = clazz.newInstance();
                BeanUtils.copyProperties(element, target);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return target;
        }).collect(Collectors.toList());
    }
}
